package com.xdwanj.filter;

import com.xdwanj.pojo.AdminUser;
import com.xdwanj.servlet.SysServlet;
import com.xdwanj.util.ConstantsStr;
import com.xdwanj.util.UrlUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SysFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String url = null;
        System.out.println("进入SysFilter过滤器...");

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        AdminUser user = (AdminUser) request.getSession().getAttribute(ConstantsStr.ADMIN_USER_SESSION);
//        String position = request.getParameter(SysServlet.METHOD);


        if (user != null) { // 已登录
            filterChain.doFilter(servletRequest, servletResponse);
        } else { // 管理员未登录
            url = request.getContextPath() + UrlUtil.getUrl(SysServlet.REQUEST_MAPPING, new String[]{SysServlet.METHOD, SysServlet.LOGIN_PAGE});
            System.out.println("url = " + url);
            response.sendRedirect(url);
            return;
        }

    }

    @Override
    public void destroy() {

    }


}
